package android.test;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.hh.fudan.project_management.NotificationService;
import com.hh.fudan.project_management.basic.Global;

import android.content.SharedPreferences;
import android.location.Location;

public class NotificationSpider extends TimerTask {

	private int num;

	public static Date lastTime;
	// 是否从通知栏进入应用
	public static boolean enterFromNotif = false;
	private NotificationService activity;

	private SharedPreferences prefs;

	public NotificationSpider(NotificationService activity,
			SharedPreferences prefs) {
		this.num = 0;
		this.activity = activity;
		this.prefs = prefs;
	}

	public void run() {
		NotificationResult result = null;

		//if (isNotifyTime()) {
			try {
				// System.out.println("hit");
				URL url = generateURL();
				result = parseResult(url);
			} catch (JDOMException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			activity.addNotification(result);
		//}

	}

	public URL generateURL() throws JDOMException, IOException {
		String paras = "?";

		Calendar calendar = Calendar.getInstance();
		if (lastTime == null) calendar.add(Calendar.MONTH, -1);
		else calendar.setTime(lastTime);
		lastTime = calendar.getTime();

		String cityName = URLEncoder.encode(prefs.getString("cityName", ""),
				"UTF-8");
		String title = URLEncoder.encode(prefs.getString("title", ""), "UTF-8");
		String price = prefs.getString("price", "");
		String discountPercent = prefs.getString("discountPercent", "");
		String members = prefs.getString("members", "0");

		paras += "createTime=" + lastTime.getTime() + "&discountPercent=" + discountPercent + "&cityName=" + cityName
				+ "&title=" + title + "&price=" + price + "&members=" + members;
		System.out.println(paras);
		URL url = new URL(Global.SERVER_URL_BASE + paras);

		return url;
	}

	@SuppressWarnings("unchecked")
	public NotificationResult parseResult(URL url) throws JDOMException,
			IOException {
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(url);
		Element root = doc.getRootElement();
		List<Element> list = root.getChildren();
		int size = list.size();
		NotificationResult result = new NotificationResult();
		result.setNum(size);
		System.out.println("团购数量:" + list.size());

		double prefLatitude = (double) prefs.getFloat("latitude", 0);
		double prefLongitude = (double) prefs.getFloat("longitude", 0);
		Location prefLocation = new Location("prefl");
		prefLocation.setLatitude(prefLatitude);
		prefLocation.setLongitude(prefLongitude);

		int prefDistance = prefs.getInt("distance", 0);

		String titles = "";
		int nearbyNum = 0;
		for (int i = 0; i < list.size(); i++) {
			titles += "(" + i + ")" + list.get(i).getChildText("title") + ";";

			Element shopsNode = list.get(i).getChild("shops");
			List<Element> shops = shopsNode.getChildren();
			boolean flag = false;
			for (int j = 0; j < shops.size(); j++) {
				Element shopNode = shops.get(j);
				double latitude = Double.parseDouble(shopNode
						.getChildText("longtitude"));
				double longitude = Double.parseDouble(shopNode
						.getChildText("latitude"));

				if ((latitude > 0) && (longitude > 0)) {
					Location location = new Location("l1");
					location.setLatitude(latitude);
					location.setLongitude(longitude);

//					System.out.println("current:" + prefLatitude + ","
//							+ prefLongitude + ";shop:" + latitude + ","
//							+ longitude);
					double distance = location.distanceTo(prefLocation);
					DecimalFormat formatter = new DecimalFormat("#.000");
//					System.out.println("distance to the shop:"
//							+ formatter.format(distance));

					if (distance < prefDistance)
						flag = true;
				}

			}
			if (flag)
				nearbyNum++;
		}

		result.setNearbyNum(nearbyNum);
		result.setContents(titles);

		return result;
	}

	public boolean isNotifyTime() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, calendar.getTime().getHours() + 8);
		Date now = calendar.getTime();

		int startHour = prefs.getInt("startHour", 0);
		int startMinute = prefs.getInt("startMinute", 0);
		calendar.set(Calendar.HOUR_OF_DAY, startHour);
		calendar.set(Calendar.MINUTE, startMinute);
		Date startTime = calendar.getTime();

		int endHour = prefs.getInt("endHour", 0);
		int endMinute = prefs.getInt("endMinute", 0);
		calendar.set(Calendar.HOUR_OF_DAY, endHour);
		calendar.set(Calendar.MINUTE, endMinute);
		Date endTime = calendar.getTime();

		System.out.println("now hour:"+now.getHours() + ":" +
		now.getMinutes() + ";startTime:"+startHour + ":" + startMinute);
		if (now.after(startTime) && (now.before(endTime)))
			return true;
		else
			return false;

	}

	public static Date getLastTime() {
		return lastTime;
	}

	public static void setLastTime(Date lastTime) {
		NotificationSpider.lastTime = lastTime;
	}

	public NotificationService getActivity() {
		return activity;
	}

	public void setActivity(NotificationService activity) {
		this.activity = activity;
	}

	public SharedPreferences getPrefs() {
		return prefs;
	}

	public void setPrefs(SharedPreferences prefs) {
		this.prefs = prefs;
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

}
